home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / tempfile.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  19KB  |  642 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Temporary files.
  5.  
  6. This module provides generic, low- and high-level interfaces for
  7. creating temporary files and directories.  The interfaces listed
  8. as "safe" just below can be used without fear of race conditions.
  9. Those listed as "unsafe" cannot, and are provided for backward
  10. compatibility only.
  11.  
  12. This module also provides some data items to the user:
  13.  
  14.   TMP_MAX  - maximum number of names that will be tried before
  15.              giving up.
  16.   template - the default prefix for all temporary names.
  17.              You may change this to control the default prefix.
  18.   tempdir  - If this is set to a string before the first use of
  19.              any routine from this module, it will be considered as
  20.              another candidate location to store temporary files.
  21. '''
  22. __all__ = [
  23.     'NamedTemporaryFile',
  24.     'TemporaryFile',
  25.     'SpooledTemporaryFile',
  26.     'mkstemp',
  27.     'mkdtemp',
  28.     'mktemp',
  29.     'TMP_MAX',
  30.     'gettempprefix',
  31.     'tempdir',
  32.     'gettempdir']
  33. import io as _io
  34. import os as _os
  35. import errno as _errno
  36. from random import Random as _Random
  37.  
  38. try:
  39.     from cStringIO import StringIO as _StringIO
  40. except ImportError:
  41.     from StringIO import StringIO as _StringIO
  42.  
  43.  
  44. try:
  45.     import fcntl as _fcntl
  46. except ImportError:
  47.     
  48.     def _set_cloexec(fd):
  49.         pass
  50.  
  51.  
  52.  
  53. def _set_cloexec(fd):
  54.     
  55.     try:
  56.         flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
  57.     except IOError:
  58.         pass
  59.  
  60.     flags |= _fcntl.FD_CLOEXEC
  61.     _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
  62.  
  63.  
  64. try:
  65.     import thread as _thread
  66. except ImportError:
  67.     import dummy_thread as _thread
  68.  
  69. _allocate_lock = _thread.allocate_lock
  70. _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
  71. if hasattr(_os, 'O_NOINHERIT'):
  72.     _text_openflags |= _os.O_NOINHERIT
  73. if hasattr(_os, 'O_NOFOLLOW'):
  74.     _text_openflags |= _os.O_NOFOLLOW
  75. _bin_openflags = _text_openflags
  76. if hasattr(_os, 'O_BINARY'):
  77.     _bin_openflags |= _os.O_BINARY
  78. if hasattr(_os, 'TMP_MAX'):
  79.     TMP_MAX = _os.TMP_MAX
  80. else:
  81.     TMP_MAX = 10000
  82. template = 'tmp'
  83. _once_lock = _allocate_lock()
  84. if hasattr(_os, 'lstat'):
  85.     _stat = _os.lstat
  86. elif hasattr(_os, 'stat'):
  87.     _stat = _os.stat
  88. else:
  89.     
  90.     def _stat(fn):
  91.         
  92.         try:
  93.             f = open(fn)
  94.         except IOError:
  95.             raise _os.error
  96.  
  97.         f.close()
  98.  
  99.  
  100. def _exists(fn):
  101.     
  102.     try:
  103.         _stat(fn)
  104.     except _os.error:
  105.         return False
  106.  
  107.     return True
  108.  
  109.  
  110. class _RandomNameSequence:
  111.     '''An instance of _RandomNameSequence generates an endless
  112.     sequence of unpredictable strings which can safely be incorporated
  113.     into file names.  Each string is six characters long.  Multiple
  114.     threads can safely use the same instance at the same time.
  115.  
  116.     _RandomNameSequence is an iterator.'''
  117.     characters = 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789_'
  118.     
  119.     def __init__(self):
  120.         self.mutex = _allocate_lock()
  121.         self.normcase = _os.path.normcase
  122.  
  123.     
  124.     def rng(self):
  125.         cur_pid = _os.getpid()
  126.         if cur_pid != getattr(self, '_rng_pid', None):
  127.             self._rng = _Random()
  128.             self._rng_pid = cur_pid
  129.         return self._rng
  130.  
  131.     rng = property(rng)
  132.     
  133.     def __iter__(self):
  134.         return self
  135.  
  136.     
  137.     def next(self):
  138.         m = self.mutex
  139.         c = self.characters
  140.         choose = self.rng.choice
  141.         m.acquire()
  142.         
  143.         try:
  144.             letters = [ choose(c) for dummy in '123456' ]
  145.         finally:
  146.             m.release()
  147.  
  148.         return self.normcase(''.join(letters))
  149.  
  150.  
  151.  
  152. def _candidate_tempdir_list():
  153.     '''Generate a list of candidate temporary directories which
  154.     _get_default_tempdir will try.'''
  155.     dirlist = []
  156.     for envname in ('TMPDIR', 'TEMP', 'TMP'):
  157.         dirname = _os.getenv(envname)
  158.         if dirname:
  159.             dirlist.append(dirname)
  160.             continue
  161.     if _os.name == 'riscos':
  162.         dirname = _os.getenv('Wimp$ScrapDir')
  163.         if dirname:
  164.             dirlist.append(dirname)
  165.         
  166.     elif _os.name == 'nt':
  167.         dirlist.extend([
  168.             'c:\\temp',
  169.             'c:\\tmp',
  170.             '\\temp',
  171.             '\\tmp'])
  172.     else:
  173.         dirlist.extend([
  174.             '/tmp',
  175.             '/var/tmp',
  176.             '/usr/tmp'])
  177.     
  178.     try:
  179.         dirlist.append(_os.getcwd())
  180.     except (AttributeError, _os.error):
  181.         dirlist.append(_os.curdir)
  182.  
  183.     return dirlist
  184.  
  185.  
  186. def _get_default_tempdir():
  187.     '''Calculate the default directory to use for temporary files.
  188.     This routine should be called exactly once.
  189.  
  190.     We determine whether or not a candidate temp dir is usable by
  191.     trying to create and write to a file in that directory.  If this
  192.     is successful, the test file is deleted.  To prevent denial of
  193.     service, the name of the test file must be randomized.'''
  194.     namer = _RandomNameSequence()
  195.     dirlist = _candidate_tempdir_list()
  196.     flags = _text_openflags
  197.     for dir in dirlist:
  198.         if dir != _os.curdir:
  199.             dir = _os.path.normcase(_os.path.abspath(dir))
  200.         for seq in xrange(100):
  201.             name = namer.next()
  202.             filename = _os.path.join(dir, name)
  203.             
  204.             try:
  205.                 fd = _os.open(filename, flags, 384)
  206.                 
  207.                 try:
  208.                     
  209.                     try:
  210.                         with _io.open(fd, 'wb', closefd = False) as fp:
  211.                             fp.write('blat')
  212.                     finally:
  213.                         _os.close(fd)
  214.  
  215.                 finally:
  216.                     _os.unlink(filename)
  217.  
  218.                 return dir
  219.             continue
  220.             except (OSError, IOError):
  221.                 e = None
  222.                 if e.args[0] != _errno.EEXIST:
  223.                     break
  224.                 
  225.             
  226.  
  227.         
  228.     
  229.     raise IOError, (_errno.ENOENT, 'No usable temporary directory found in %s' % dirlist)
  230.  
  231. _name_sequence = None
  232.  
  233. def _get_candidate_names():
  234.     '''Common setup sequence for all user-callable interfaces.'''
  235.     global _name_sequence
  236.     if _name_sequence is None:
  237.         _once_lock.acquire()
  238.         
  239.         try:
  240.             if _name_sequence is None:
  241.                 _name_sequence = _RandomNameSequence()
  242.         finally:
  243.             _once_lock.release()
  244.  
  245.     return _name_sequence
  246.  
  247.  
  248. def _mkstemp_inner(dir, pre, suf, flags):
  249.     '''Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.'''
  250.     names = _get_candidate_names()
  251.     for seq in xrange(TMP_MAX):
  252.         name = names.next()
  253.         file = _os.path.join(dir, pre + name + suf)
  254.         
  255.         try:
  256.             fd = _os.open(file, flags, 384)
  257.             _set_cloexec(fd)
  258.             return (fd, _os.path.abspath(file))
  259.         continue
  260.         except OSError:
  261.             e = None
  262.             if e.errno == _errno.EEXIST:
  263.                 continue
  264.             if _os.name == 'nt' and e.errno == _errno.EACCES:
  265.                 continue
  266.             raise 
  267.             continue
  268.         
  269.  
  270.     
  271.     raise IOError, (_errno.EEXIST, 'No usable temporary file name found')
  272.  
  273.  
  274. def gettempprefix():
  275.     '''Accessor for tempdir.template.'''
  276.     return template
  277.  
  278. tempdir = None
  279.  
  280. def gettempdir():
  281.     '''Accessor for tempfile.tempdir.'''
  282.     global tempdir
  283.     if tempdir is None:
  284.         _once_lock.acquire()
  285.         
  286.         try:
  287.             if tempdir is None:
  288.                 tempdir = _get_default_tempdir()
  289.         finally:
  290.             _once_lock.release()
  291.  
  292.     return tempdir
  293.  
  294.  
  295. def mkstemp(suffix = '', prefix = template, dir = None, text = False):
  296.     """User-callable function to create and return a unique temporary
  297.     file.  The return value is a pair (fd, name) where fd is the
  298.     file descriptor returned by os.open, and name is the filename.
  299.  
  300.     If 'suffix' is specified, the file name will end with that suffix,
  301.     otherwise there will be no suffix.
  302.  
  303.     If 'prefix' is specified, the file name will begin with that prefix,
  304.     otherwise a default prefix is used.
  305.  
  306.     If 'dir' is specified, the file will be created in that directory,
  307.     otherwise a default directory is used.
  308.  
  309.     If 'text' is specified and true, the file is opened in text
  310.     mode.  Else (the default) the file is opened in binary mode.  On
  311.     some operating systems, this makes no difference.
  312.  
  313.     The file is readable and writable only by the creating user ID.
  314.     If the operating system uses permission bits to indicate whether a
  315.     file is executable, the file is executable by no one. The file
  316.     descriptor is not inherited by children of this process.
  317.  
  318.     Caller is responsible for deleting the file when done with it.
  319.     """
  320.     if dir is None:
  321.         dir = gettempdir()
  322.     if text:
  323.         flags = _text_openflags
  324.     else:
  325.         flags = _bin_openflags
  326.     return _mkstemp_inner(dir, prefix, suffix, flags)
  327.  
  328.  
  329. def mkdtemp(suffix = '', prefix = template, dir = None):
  330.     """User-callable function to create and return a unique temporary
  331.     directory.  The return value is the pathname of the directory.
  332.  
  333.     Arguments are as for mkstemp, except that the 'text' argument is
  334.     not accepted.
  335.  
  336.     The directory is readable, writable, and searchable only by the
  337.     creating user.
  338.  
  339.     Caller is responsible for deleting the directory when done with it.
  340.     """
  341.     if dir is None:
  342.         dir = gettempdir()
  343.     names = _get_candidate_names()
  344.     for seq in xrange(TMP_MAX):
  345.         name = names.next()
  346.         file = _os.path.join(dir, prefix + name + suffix)
  347.         
  348.         try:
  349.             _os.mkdir(file, 448)
  350.             return file
  351.         continue
  352.         except OSError:
  353.             e = None
  354.             if e.errno == _errno.EEXIST:
  355.                 continue
  356.             raise 
  357.             continue
  358.         
  359.  
  360.     
  361.     raise IOError, (_errno.EEXIST, 'No usable temporary directory name found')
  362.  
  363.  
  364. def mktemp(suffix = '', prefix = template, dir = None):
  365.     """User-callable function to return a unique temporary file name.  The
  366.     file is not created.
  367.  
  368.     Arguments are as for mkstemp, except that the 'text' argument is
  369.     not accepted.
  370.  
  371.     This function is unsafe and should not be used.  The file name
  372.     refers to a file that did not exist at some point, but by the time
  373.     you get around to creating it, someone else may have beaten you to
  374.     the punch.
  375.     """
  376.     if dir is None:
  377.         dir = gettempdir()
  378.     names = _get_candidate_names()
  379.     for seq in xrange(TMP_MAX):
  380.         name = names.next()
  381.         file = _os.path.join(dir, prefix + name + suffix)
  382.         if not _exists(file):
  383.             return file
  384.     
  385.     raise IOError, (_errno.EEXIST, 'No usable temporary filename found')
  386.  
  387.  
  388. class _TemporaryFileWrapper:
  389.     '''Temporary file wrapper
  390.  
  391.     This class provides a wrapper around files opened for
  392.     temporary use.  In particular, it seeks to automatically
  393.     remove the file when it is no longer needed.
  394.     '''
  395.     
  396.     def __init__(self, file, name, delete = True):
  397.         self.file = file
  398.         self.name = name
  399.         self.close_called = False
  400.         self.delete = delete
  401.  
  402.     
  403.     def __getattr__(self, name):
  404.         file = self.__dict__['file']
  405.         a = getattr(file, name)
  406.         if not issubclass(type(a), type(0)):
  407.             setattr(self, name, a)
  408.         return a
  409.  
  410.     
  411.     def __enter__(self):
  412.         self.file.__enter__()
  413.         return self
  414.  
  415.     if _os.name != 'nt':
  416.         unlink = _os.unlink
  417.         
  418.         def close(self):
  419.             if not self.close_called:
  420.                 self.close_called = True
  421.                 self.file.close()
  422.                 if self.delete:
  423.                     self.unlink(self.name)
  424.                 
  425.  
  426.         
  427.         def __del__(self):
  428.             self.close()
  429.  
  430.         
  431.         def __exit__(self, exc, value, tb):
  432.             result = self.file.__exit__(exc, value, tb)
  433.             self.close()
  434.             return result
  435.  
  436.     else:
  437.         
  438.         def __exit__(self, exc, value, tb):
  439.             self.file.__exit__(exc, value, tb)
  440.  
  441.  
  442.  
  443. def NamedTemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None, delete = True):
  444.     '''Create and return a temporary file.
  445.     Arguments:
  446.     \'prefix\', \'suffix\', \'dir\' -- as for mkstemp.
  447.     \'mode\' -- the mode argument to os.fdopen (default "w+b").
  448.     \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  449.     \'delete\' -- whether the file is deleted on close (default True).
  450.     The file is created as mkstemp() would do it.
  451.  
  452.     Returns an object with a file-like interface; the name of the file
  453.     is accessible as file.name.  The file will be automatically deleted
  454.     when it is closed unless the \'delete\' argument is set to False.
  455.     '''
  456.     if dir is None:
  457.         dir = gettempdir()
  458.     if 'b' in mode:
  459.         flags = _bin_openflags
  460.     else:
  461.         flags = _text_openflags
  462.     if _os.name == 'nt' and delete:
  463.         flags |= _os.O_TEMPORARY
  464.     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  465.     file = _os.fdopen(fd, mode, bufsize)
  466.     return _TemporaryFileWrapper(file, name, delete)
  467.  
  468. if _os.name != 'posix' or _os.sys.platform == 'cygwin':
  469.     TemporaryFile = NamedTemporaryFile
  470. else:
  471.     
  472.     def TemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  473.         '''Create and return a temporary file.
  474.         Arguments:
  475.         \'prefix\', \'suffix\', \'dir\' -- as for mkstemp.
  476.         \'mode\' -- the mode argument to os.fdopen (default "w+b").
  477.         \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  478.         The file is created as mkstemp() would do it.
  479.  
  480.         Returns an object with a file-like interface.  The file has no
  481.         name, and will cease to exist when it is closed.
  482.         '''
  483.         if dir is None:
  484.             dir = gettempdir()
  485.         if 'b' in mode:
  486.             flags = _bin_openflags
  487.         else:
  488.             flags = _text_openflags
  489.         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  490.         
  491.         try:
  492.             _os.unlink(name)
  493.             return _os.fdopen(fd, mode, bufsize)
  494.         except:
  495.             _os.close(fd)
  496.             raise 
  497.  
  498.  
  499.  
  500. class SpooledTemporaryFile:
  501.     '''Temporary file wrapper, specialized to switch from
  502.     StringIO to a real file when it exceeds a certain size or
  503.     when a fileno is needed.
  504.     '''
  505.     _rolled = False
  506.     
  507.     def __init__(self, max_size = 0, mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  508.         self._file = _StringIO()
  509.         self._max_size = max_size
  510.         self._rolled = False
  511.         self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
  512.  
  513.     
  514.     def _check(self, file):
  515.         if self._rolled:
  516.             return None
  517.         max_size = None._max_size
  518.         if max_size and file.tell() > max_size:
  519.             self.rollover()
  520.  
  521.     
  522.     def rollover(self):
  523.         if self._rolled:
  524.             return None
  525.         file = None._file
  526.         newfile = self._file = TemporaryFile(*self._TemporaryFileArgs)
  527.         del self._TemporaryFileArgs
  528.         newfile.write(file.getvalue())
  529.         newfile.seek(file.tell(), 0)
  530.         self._rolled = True
  531.  
  532.     
  533.     def __enter__(self):
  534.         if self._file.closed:
  535.             raise ValueError('Cannot enter context with closed file')
  536.         return self
  537.  
  538.     
  539.     def __exit__(self, exc, value, tb):
  540.         self._file.close()
  541.  
  542.     
  543.     def __iter__(self):
  544.         return self._file.__iter__()
  545.  
  546.     
  547.     def close(self):
  548.         self._file.close()
  549.  
  550.     
  551.     def closed(self):
  552.         return self._file.closed
  553.  
  554.     closed = property(closed)
  555.     
  556.     def fileno(self):
  557.         self.rollover()
  558.         return self._file.fileno()
  559.  
  560.     
  561.     def flush(self):
  562.         self._file.flush()
  563.  
  564.     
  565.     def isatty(self):
  566.         return self._file.isatty()
  567.  
  568.     
  569.     def mode(self):
  570.         
  571.         try:
  572.             return self._file.mode
  573.         except AttributeError:
  574.             return self._TemporaryFileArgs[0]
  575.  
  576.  
  577.     mode = property(mode)
  578.     
  579.     def name(self):
  580.         
  581.         try:
  582.             return self._file.name
  583.         except AttributeError:
  584.             return None
  585.  
  586.  
  587.     name = property(name)
  588.     
  589.     def next(self):
  590.         return self._file.next
  591.  
  592.     
  593.     def read(self, *args):
  594.         return self._file.read(*args)
  595.  
  596.     
  597.     def readline(self, *args):
  598.         return self._file.readline(*args)
  599.  
  600.     
  601.     def readlines(self, *args):
  602.         return self._file.readlines(*args)
  603.  
  604.     
  605.     def seek(self, *args):
  606.         self._file.seek(*args)
  607.  
  608.     
  609.     def softspace(self):
  610.         return self._file.softspace
  611.  
  612.     softspace = property(softspace)
  613.     
  614.     def tell(self):
  615.         return self._file.tell()
  616.  
  617.     
  618.     def truncate(self):
  619.         self._file.truncate()
  620.  
  621.     
  622.     def write(self, s):
  623.         file = self._file
  624.         rv = file.write(s)
  625.         self._check(file)
  626.         return rv
  627.  
  628.     
  629.     def writelines(self, iterable):
  630.         file = self._file
  631.         rv = file.writelines(iterable)
  632.         self._check(file)
  633.         return rv
  634.  
  635.     
  636.     def xreadlines(self, *args):
  637.         if hasattr(self._file, 'xreadlines'):
  638.             return iter(self._file)
  639.         return None(self._file.readlines(*args))
  640.  
  641.  
  642.